package org.toy.wechat.gym.service.impl;

import com.mzlion.core.lang.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.toy.wechat.core.common.enums.BaseResultEnum;
import org.toy.wechat.core.common.exception.BusinessException;
import org.toy.wechat.core.common.utils.BeanUtil;
import org.toy.wechat.core.common.utils.DateUtil;
import org.toy.wechat.core.common.utils.StringUtil;
import org.toy.wechat.gym.cache.UserCache;
import org.toy.wechat.gym.dao.GymBmiInfoMapper;
import org.toy.wechat.gym.domain.GymBmiInfo;
import org.toy.wechat.gym.redis.RedisClientTemplate;
import org.toy.wechat.gym.request.GymBmiRequest;
import org.toy.wechat.gym.service.IGymBmiInfoService;

/**
 * @Description TODO
 * @Author devin
 * @Date: 2020/2/22 0022 20:59
 */
@Service
@Slf4j
public class GymBmiInfoServiceImpl implements IGymBmiInfoService {

    @Autowired
    private GymBmiInfoMapper gymBmiInfoMapper;

    @Autowired
    private UserCache userCache;

    @Autowired
    private RedisClientTemplate redisClientTemplate;


    @Override
    public void insert(GymBmiRequest gymBmiRequest) {
        String openId = gymBmiRequest.getOpenId();
        String timeLimitKey = getTimeLimitKey(openId);
        if (redisClientTemplate.exists(timeLimitKey) && redisClientTemplate.incr(timeLimitKey) > 50) {
            return;
        }
        String interfaceKey = getInterfaceLimitKey(openId);
        if (!doLimit(timeLimitKey, DateUtil.getSecondsTobeforedawn(), 50)) {
            log.info("报告有人刷接口，{}", openId);
            return;
        }
        if (!doLimit(interfaceKey, 60, 3)) {
            log.info("报告有人刷接口1分钟超过三次，{}", openId);
            return;
        }
        String openIdTemp = userCache.get(openId, String.class);
        if (StringUtils.isEmpty(openIdTemp)) {
            throw new BusinessException(BaseResultEnum.USER_NOT_LOGIN);
        }
        GymBmiInfo gymBmiInfo = BeanUtil.copy(gymBmiRequest, GymBmiInfo.class);
        gymBmiInfoMapper.insertSelective(gymBmiInfo);
    }


    public boolean doLimit(String key, int time, int value) {
        String keyValue = redisClientTemplate.get(key);
        if (!StringUtils.isEmpty(keyValue)) {
            if (Integer.parseInt(redisClientTemplate.get(key)) > value) {
                return false;
            }
        }
        if (redisClientTemplate.incr(key) > value) {
            redisClientTemplate.expire(key, time);
            return false;
        }
        redisClientTemplate.expire(key, time);
        return true;
    }

    private String getTimeLimitKey(String openId) {
        return String.format("TIME_LIMIT_%S", openId);
    }

    private String getInterfaceLimitKey(String openId) {
        return String.format("INTERFACE_LIMIT_%S", openId);
    }
}
